<script setup>
import { ref, watch ,onMounted } from 'vue'
import { queryClazzsApi,addClazzApi,deleteClazzApi,queryClazzByIdApi,updateClazzApi } from '@/api/clazz';
import { queryAllApi } from '@/api/emp';
import { ElMessage, ElMessageBox } from 'element-plus';

const searchClazz=ref({name:'',date:[],begin:'',end:''});
const clazzList=ref([]);
const currentPage = ref(1) // 当前页
const pageSize = ref(10) // 每页显示条目数
const background = ref(true)  /// 是否显示背景
const total=ref(0); // 总条数
const subjectList=ref([{id:1,name:'Java'},{id:2,name:'前端'},{id:3,name:'大数据'},
                       {id:4,name:'Python'},{id:5,name:'Go'},{id:6,name:'嵌入式'}
]);

onMounted(()=>{
  search();
  getTeacherList();
})

const search= async ()=>{
  let result= await queryClazzsApi(searchClazz.value.name,searchClazz.value.begin,searchClazz.value.end,currentPage.value,pageSize.value);
  if(result.code){
    clazzList.value=result.data.rows;
    total.value=result.data.total;
  }else{
    ElMessage.error(result.msg);
  }
};

const handleSizeChange = () => {
  search();
}
const handleCurrentChange = () => {
  search();
}

//侦听date数据,date改变时将其赋值给clazz.value.begin和end
watch(() => searchClazz.value.date,(newVal,oldVal)=>{
  if( newVal.length!==null && newVal.length==2){
    searchClazz.value.begin=newVal[0];
    searchClazz.value.end=newVal[1];
  }else{
    searchClazz.value.begin='';
    searchClazz.value.end='';
  }
});

const clear=()=>{
  searchClazz.value={name:'',gender:'',date:[],begin:'',end:''};
  search();
}

const dialogVisible=ref(false);
const dialogTitle=ref('');

//新增班级
const addClazz=()=>{
  clazz.value={
    name: '',
    room: '',
    beginDate: '',
    endDate: '',
    masterId: '',
    subject: ''
  }
  dialogVisible.value=true;
  dialogTitle.value='新增班级';
  if(clazzFromref.value){
    clazzFromref.value.resetFields();
  }
};
//新增,修改班级表单 
const clazz=ref({
  name: '',
  room: '',
  beginDate: '',
  endDate: '',
  masterId: '',
  subject: ''
});

//班主任列表
const teacherList=ref([]);
const getTeacherList= async ()=>{
  const result= await queryAllApi(); //返回的是所有员工
  // 确保接口响应成功且数据合法
  if (result.code === 1 && Array.isArray(result.data)) {
    // 筛选 job 为 1 的班主任
    const filteredTeachers = result.data.filter(teacher => teacher.job === 1);
    teacherList.value = filteredTeachers; // 覆盖原有数据
  } else {
    // 可选：处理数据异常情况（如清空列表）
    teacherList.value = [];
  }
}

//表单校验规则
const rules = ref({
  name: [
    { required: true, message: '请输入班级姓名', trigger: 'blur' }
  ],
  room: [
    { required: true, message: '请输入教室号', trigger: 'blur' }
  ],
  subject: [
    { required: true, message: '请选择学科方向', trigger: 'change' }
  ],
  beginDate:[
    { required: true, message: '请选择开始时间', trigger: 'change' }
  ],
  endDate:[
    { required: true, message: '请选择结束时间', trigger: 'change' }
  ]
});

const clazzFromref=ref();

const save=()=>{
  if(!clazzFromref.value) return ;
  clazzFromref.value.validate(async valid=>{
    if(valid){
      let result;
      if(clazz.value.id){
        result=await updateClazzApi(clazz.value);
      }else{
        result= await addClazzApi(clazz.value);
      }

      if(result.code){
          ElMessage.success("保存成功");
          dialogVisible.value=false;
          search(); //刷新
        }else{
          ElMessage.error(msg);
        }
    }else{
      ElMessage.error("请按正确的格式!");
    }
  });
};

//删除班级
const delById=(id)=>{
  ElMessageBox.confirm(
    '你真的要删除吗?',
    'Warning',
    {
      confirmButtonText: 'OK',
      cancelButtonText: 'Cancel',
      type: 'warning',
    }
  ).then(
    async ()=>{
        const result=await deleteClazzApi(id);
        if(result.code){
          ElMessage.success("删除成功");
          search(); //刷新
        }else{
          ElMessage.error("删除失败, "+result.msg);
        }
    }
  ).catch(()=>{
    ElMessage.info("删除取消");
  });
};
//通过id编辑班级
const edit= async (id)=>{
  const result=await queryClazzByIdApi(id);
  dialogVisible.value=true;
  dialogTitle.value='编辑班级';
  if(result.code){
    clazz.value=result.data;
    dialogVisible.value=true;
    dialogTitle.value='编辑班级';
  }else{
    ElMessage.error(result.msg);
  }
};

</script>

<template>
  <h1>班级管理</h1>
  <div class="container">
    <!-- 班级搜索栏 -->
      <el-form :inline="true" :model="searchClazz" class="demo-form-inline">
        <el-form-item label="班级名称:">
          <el-input v-model="searchClazz.name" placeholder="请输入班级名称" clearable style="width: 150px;"/>
        </el-form-item>
        <el-form-item label="结课日期:">
            <el-date-picker
            v-model="searchClazz.date"
            type="daterange"
            range-separator="到"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            style="width: 230px;"
            value-format="YYYY-MM-DD"
            clearable
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="search">查询</el-button>
          <el-button type="warning" @click="clear">清空</el-button>
        </el-form-item>
      </el-form>
  </div>
  <!-- 新增班级 -->
  <div class="container">
      <el-button type="success" @click="addClazz">+ 新增班级</el-button>
   </div>
  <!-- 班级列表 -->
  <div class="container">
      <el-table :data="clazzList" border style="width: 100%"> 
        <!-- 多选框 -->
        <el-table-column type="index" label="序号" width="55" align="center" /> 
        <el-table-column prop="name" label="班级名称" width="170" align="center"/>
        <el-table-column prop="room" label="班级教室"  width="120" align="center"/>
        <el-table-column prop="masterName" label="班主任"  width="120" align="center"/>
        <el-table-column prop="beginDate" label="开课时间"  width="120" align="center"/>
        <el-table-column prop="endDate" label="结课时间"  width="120" align="center"/>
        <el-table-column prop="status" label="状态"  width="120" align="center"/>
        <el-table-column prop="updateTime" label="最后操作时间"  width="180" align="center"/>
        <el-table-column label="操作"  width="180" align="center">
          <template #default="scope">
          <el-button type="primary" size="small" @click="edit(scope.row.id)"><el-icon><EditPen /></el-icon>编辑</el-button>
          <el-button type="danger" size="small" @click="delById(scope.row.id)"><el-icon><Delete /></el-icon>删除</el-button>
        </template>
        </el-table-column>
      </el-table>
   </div>
   <!-- 分页条 -->
   <div class="container">
    <el-pagination
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :page-sizes="[5,10,15,20,30,40,50]"
      :background="background"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
   </div>

   <!-- 新增班级/修改班级对话框 -->
   <el-dialog v-model="dialogVisible" :title="dialogTitle" width="40%">
    <el-form :model="clazz" :rules="rules" ref="clazzFromref">
      <el-form-item label="班级名称" label-width="80px" prop="name">
        <el-input v-model="clazz.name" placeholder="请输入班级名称" />
      </el-form-item>
      <el-form-item label="班级教室" label-width="80px" prop="room">
        <el-input v-model="clazz.room" placeholder="请输入班级教室" />
      </el-form-item>
      <el-form-item label="开始时间" label-width="80px" prop="beginDate">
         <el-date-picker
          v-model="clazz.beginDate"
          type="date"
          placeholder="选择开始日期"
          value-format="YYYY-MM-DD"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="结束时间" label-width="80px" prop="endDate">
         <el-date-picker
          v-model="clazz.endDate"
          type="date"
          placeholder="选择结束日期"
          value-format="YYYY-MM-DD"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="班主任" label-width="80px">
          <el-select v-model="clazz.masterId" placeholder="请选择">
            <el-option
              v-for="item in teacherList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
      </el-form-item>
      <el-form-item label="学科" label-width="80px" prop="subject">
          <el-select v-model="clazz.subject" placeholder="请选择">
            <el-option
              v-for="item in subjectList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
      </el-form-item>
      
    </el-form>

    <template #footer>
      <el-button @click="dialogVisible=false">取消</el-button>
      <el-button type="primary" @click="save">保存</el-button>
    </template>
  </el-dialog>


</template>

<style scoped>
.container{
  margin-top: 15px;
}

</style>